package org.ww.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.ww.oss.service.OssService;
import org.ww.oss.utils.ConstantsPropertiesUtils;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFile(MultipartFile file) {
        // 根据配置文件将相应得参数得到
        String endpoint = ConstantsPropertiesUtils.END_POINT;
        String accessKeyId = ConstantsPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantsPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantsPropertiesUtils.BUCKET_NAME;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String fileName = file.getOriginalFilename();

            //1 让文件是唯一得一个值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=uuid+fileName;

            //2 让文件按照日期得时间去上传到上边
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName=datePath+fileName;
            //上传文件
            ossClient.putObject(bucketName, fileName, inputStream);



            // 关闭OSSClient。
            ossClient.shutdown();
            //手动拼接返回得url
            //https://ww-edu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url="https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
